<template>
  <div class="app-container">
    <el-card shadow="never" v-loading="loading">
      <template #header>
        <div class="card-header">
          <h3>排班详情</h3>
          <div class="header-actions">
            <el-button 
              type="danger" 
              v-if="scheduleData.status === '正常'"
              @click="handleCancel"
              v-permission="'schedule:delete'"
            >
              取消排班
            </el-button>
            <el-button @click="goBack">返回</el-button>
          </div>
        </div>
      </template>
      
      <div v-if="scheduleData.id">
        <el-descriptions title="基本信息" :column="3" border>
          <el-descriptions-item label="排班编号">{{ scheduleData.id }}</el-descriptions-item>
          <el-descriptions-item label="挂号类型">{{ scheduleData.registrationType }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="scheduleData.status === '正常' ? 'success' : 'danger'">
              {{ scheduleData.status }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="诊室">{{ scheduleData.room }}</el-descriptions-item>
          <el-descriptions-item label="挂号费">￥{{ scheduleData.registrationFee }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ formatDate(scheduleData.createdAt) }}</el-descriptions-item>
        </el-descriptions>
        
        <el-divider />
        
        <el-descriptions title="医生信息" :column="3" border>
          <el-descriptions-item label="姓名">{{ scheduleData.doctorInfo?.name }}</el-descriptions-item>
          <el-descriptions-item label="工号">{{ scheduleData.doctorInfo?.staffId }}</el-descriptions-item>
          <el-descriptions-item label="职称">{{ scheduleData.doctorInfo?.title }}</el-descriptions-item>
        </el-descriptions>
        
        <el-divider />
        
        <el-descriptions title="科室信息" :column="3" border>
          <el-descriptions-item label="科室名称">{{ scheduleData.departmentInfo?.name }}</el-descriptions-item>
          <el-descriptions-item label="科室位置">{{ scheduleData.departmentInfo?.location || '-' }}</el-descriptions-item>
        </el-descriptions>
        
        <el-divider />
        
        <!-- 时间段信息卡片 -->
        <el-row :gutter="20">
          <el-col :span="12" v-for="slot in scheduleData.timeSlots" :key="slot.period">
            <el-card class="time-slot-card" shadow="hover">
              <div class="time-slot-header">
                <el-tag :type="getTimeSlotType(slot.period)" size="large">{{ slot.period }}</el-tag>
                <span class="time-slot-time">{{ slot.startTime }} - {{ slot.endTime }}</span>
              </div>
              <div class="time-slot-info">
                <div class="info-row">
                  <span class="info-label">总容量：</span>
                  <span class="info-value">{{ slot.capacity }}人</span>
                </div>
                <div class="info-row">
                  <span class="info-label">剩余号源：</span>
                  <el-tag :type="getCapacityTagType(scheduleData.remainingCapacity[slot.period], slot.capacity)">
                    {{ scheduleData.remainingCapacity[slot.period] }}
                  </el-tag>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>

        <el-divider />
        
        <!-- 预约记录卡片 -->
        <el-card class="appointments-card">
          <template #header>
            <div class="section-header">
              <h4>预约记录</h4>
              <div class="appointment-stats">
                <el-tag v-for="slot in scheduleData.timeSlots" :key="slot.period" :type="getTimeSlotType(slot.period)">
                  {{ slot.period }}: {{ getAppointmentCount(slot.period) }}/{{ slot.capacity }}
                </el-tag>
              </div>
            </div>
          </template>
          
          <el-table
            :data="scheduleData.appointments || []"
            style="width: 100%"
            border
            stripe
            v-loading="loading"
          >
            <el-table-column prop="appointmentId" label="预约编号" min-width="150" />
            <el-table-column prop="patientName" label="患者姓名" min-width="120">
              <template #default="scope">
                <el-button type="text" @click="viewPatient(scope.row.patientId)">
                  {{ scope.row.patientName }}
                </el-button>
              </template>
            </el-table-column>
            <el-table-column prop="period" label="时间段" width="100">
              <template #default="scope">
                <el-tag :type="getTimeSlotType(scope.row.period)">{{ scope.row.period }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="timeSlot" label="预约时段" min-width="150" />
            <el-table-column prop="status" label="状态" width="100">
              <template #default="scope">
                <el-tag :type="getAppointmentStatusType(scope.row.status)">{{ scope.row.status }}</el-tag>
              </template>
            </el-table-column>
          </el-table>
          
          <div v-if="!scheduleData.appointments?.length" class="empty-data">
            暂无预约记录
          </div>
        </el-card>
      </div>
    </el-card>
    
    <!-- 取消排班对话框 -->
    <el-dialog
      v-model="cancelDialogVisible"
      title="取消排班"
      width="500px"
    >
      <div class="cancel-warning">
        <el-alert
          title="取消排班将会影响已预约的患者"
          type="warning"
          description="取消排班后，该时段内的所有预约将被标记为已取消，并通知相关患者。"
          show-icon
          :closable="false"
        />
      </div>
      
      <el-form :model="cancelForm" ref="cancelFormRef" label-width="100px">
        <el-form-item label="取消原因" prop="reason" required>
          <el-input
            v-model="cancelForm.reason"
            type="textarea"
            placeholder="请输入取消原因"
            :rows="3"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmCancel" :loading="cancelLoading">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { scheduleAPI } from '@/utils/api'
import { formatDate } from '@/utils/date'

// 路由相关
const route = useRoute()
const router = useRouter()
const scheduleId = ref(route.params.id)

// 数据加载状态
const loading = ref(false)
const cancelLoading = ref(false)

// 排班数据
const scheduleData = ref({})

// 取消排班对话框
const cancelDialogVisible = ref(false)
const cancelFormRef = ref(null)
const cancelForm = reactive({
  reason: ''
})

// 获取时间段标签类型
const getTimeSlotType = (period) => {
  switch (period) {
    case '上午':
      return 'success'
    case '下午':
      return 'warning'
    case '晚上':
      return 'info'
    default:
      return ''
  }
}

// 获取剩余号源标签类型
const getCapacityTagType = (remaining, total) => {
  if (!total) return 'info'
  const ratio = remaining / total
  if (ratio <= 0.2) return 'danger'
  if (ratio <= 0.5) return 'warning'
  return 'success'
}

// 获取预约状态标签类型
const getAppointmentStatusType = (status) => {
  switch (status) {
    case '预约中':
      return 'warning'
    case '已完成':
      return 'success'
    case '已取消':
      return 'info'
    case '已爽约':
      return 'danger'
    default:
      return ''
  }
}

// 获取预约统计信息
const getAppointmentStats = () => {
  const stats = {}
  if (!scheduleData.value.timeSlots) return stats

  // 初始化每个时间段的预约数为0
  scheduleData.value.timeSlots.forEach(slot => {
    stats[slot.period] = 0
  })

  // 统计每个时间段的预约数
  if (scheduleData.value.appointments) {
    scheduleData.value.appointments.forEach(appointment => {
      if (appointment.status === '预约中') {
        stats[appointment.period] = (stats[appointment.period] || 0) + 1
      }
    })
  }

  return stats
}

// 获取时间段总容量
const getTotalCapacity = (period) => {
  const slot = scheduleData.value.timeSlots?.find(s => s.period === period)
  return slot ? slot.capacity : 0
}

// 获取排班详情
const getScheduleDetail = async () => {
  loading.value = true
  try {
    const res = await scheduleAPI.getSchedule(scheduleId.value)
    scheduleData.value = res.data
  } catch (error) {
    console.error('获取排班详情失败', error)
    ElMessage.error('获取排班详情失败')
  } finally {
    loading.value = false
  }
}

// 取消排班
const handleCancel = () => {
  cancelForm.reason = ''
  cancelDialogVisible.value = true
}

// 确认取消排班
const confirmCancel = async () => {
  if (!cancelForm.reason) {
    ElMessage.warning('请输入取消原因')
    return
  }
  
  cancelLoading.value = true
  try {
    await scheduleAPI.deleteSchedule(scheduleId.value, { 
      reason: cancelForm.reason 
    })
    ElMessage.success('排班已取消')
    cancelDialogVisible.value = false
    getScheduleDetail()
  } catch (error) {
    ElMessage.error(error.message || '取消排班失败')
  } finally {
    cancelLoading.value = false
  }
}

// 返回上一页
const goBack = () => {
  router.go(-1)
}

// 查看患者详情
const viewPatient = (patientId) => {
  router.push(`/patients/detail/${patientId}`)
}

// 获取指定时间段的预约数量
const getAppointmentCount = (period) => {
  if (!scheduleData.value.appointments) return 0
  return scheduleData.value.appointments.filter(
    appointment => appointment.period === period && appointment.status === '预约中'
  ).length
}

// 页面加载时获取数据
onMounted(() => {
  if (scheduleId.value) {
    getScheduleDetail()
  } else {
    ElMessage.error('参数错误')
    goBack()
  }
})
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.time-slot-card {
  margin-bottom: 20px;
  height: 100%;
}

.time-slot-header {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.time-slot-time {
  margin-left: 15px;
  font-size: 18px;
  font-weight: bold;
  color: #606266;
}

.time-slot-info {
  padding: 10px 0;
}

.info-row {
  display: flex;
  align-items: center;
  margin: 10px 0;
}

.info-label {
  color: #909399;
  margin-right: 10px;
  width: 80px;
}

.info-value {
  font-weight: bold;
  color: #606266;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.appointment-stats {
  display: flex;
  gap: 10px;
}

.empty-data {
  text-align: center;
  color: #909399;
  padding: 30px 0;
  font-size: 14px;
}

.appointments-card {
  margin-top: 20px;
}

.cancel-warning {
  margin-bottom: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style> 